package com.sam.im.sms.index.activitys;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;
import android.telephony.SubscriptionManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.sms.R;
import com.sam.im.sms.base.BaseActivity;
import com.sam.im.sms.widgets.SlideBackLayout;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述
 * liuyucheng
 * Created By 刘育成 on 2019/5/31.
 */
public class NewSmsActivity extends BaseActivity implements View.OnClickListener {
    private static String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
    private static String SMS_DELIVERED_ACTION = "SMS_DELIVERED_ACTION";
    private ImageView contact;
    private TextView textView;
    private EditText mEditText;
    private EditText ed_context;
    private TextView txt_sim1;
    private LinearLayout ll_send_layout_sim1;
    private LinearLayout ll_send_layout_sim2;
    private TextView tv_back;
    String name;
    String number;
    String address;
    String message;
    private int subIdOne, subIdTwo;
    private boolean isState = false;
    private mServiceReceiver mSendReceiver, mDeliveredReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_new_sms;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    public void init(Bundle savedInstanceState) {
        contact = findViewById(R.id.contact);
        textView = findViewById(R.id.textView);
        mEditText = findViewById(R.id.ed_txt);
        ed_context = findViewById(R.id.ed_context);
        ll_send_layout_sim1 = findViewById(R.id.ll_send_layout_sim1);
        ll_send_layout_sim2 = findViewById(R.id.ll_send_layout_sim2);
        txt_sim1 = findViewById(R.id.txt_sim1);
        tv_back = findViewById(R.id.tv_back);
        textView.setText("新建信息");
        contact.setOnClickListener(this);
        ll_send_layout_sim1.setOnClickListener(this);
        ll_send_layout_sim2.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        if (SubscriptionManager.from(this).getActiveSubscriptionInfoCount() == 1) {
            isState = true;
            txt_sim1.setVisibility(View.GONE);
            ll_send_layout_sim2.setVisibility(View.GONE);
        } else {
            isState = false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.contact:
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(intent, 1);
                break;
            case R.id.ll_send_layout_sim1:
                if (ContextCompat.checkSelfPermission(NewSmsActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(NewSmsActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1000);
                } else if (ContextCompat.checkSelfPermission(NewSmsActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(NewSmsActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1000);
                } else {
                    sendMsg();
                }
                break;
            case R.id.ll_send_layout_sim2:
                if (ContextCompat.checkSelfPermission(NewSmsActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(NewSmsActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1000);
                } else if (ContextCompat.checkSelfPermission(NewSmsActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(NewSmsActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1000);
                } else {
                    isState = false;
                    sendMsg();
                }
                break;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    private void sendMsg() {
        String edit = mEditText.getText().toString();
        String content = ed_context.getText().toString();
        if (TextUtils.isEmpty(number)) {
            if (TextUtils.isEmpty(edit)) {
                showToast("请输入收件人手机号");
                return;
            } else {
                address = edit;
            }
        } else {
            address = number;
        }
        if (TextUtils.isEmpty(content)) {
            showToast("请输入内容");
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE);
            Class sclass = subscriptionManager.getClass();
            Method getSubId = null;
            try {
                getSubId = sclass.getDeclaredMethod("getSubId", int.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int[] ints = new int[1];
            try {
                ints = (int[]) getSubId.invoke(subscriptionManager, 0);
                subIdOne = ints[0];
                ints = (int[]) getSubId.invoke(subscriptionManager, 1);
                subIdTwo = ints[0];
            } catch (Exception e) {
                e.printStackTrace();
            }
            //动态注册2个广播--发送成功，对方接收成功
            Intent itSend = new Intent(SMS_SEND_ACTIOIN);
            Intent itDeliver = new Intent(SMS_DELIVERED_ACTION);
            PendingIntent mSendPI = PendingIntent.getBroadcast(getApplicationContext(), 0, itSend, 0);
            PendingIntent mDeliverPI = PendingIntent.getBroadcast(getApplicationContext(), 0, itDeliver, 0);
            if (isState) {
                SmsManager smsManager = SmsManager.getDefault();
                ArrayList<String> divideContents = smsManager.divideMessage(content);
                for (String msg : divideContents) {
                    message = msg;
                    smsManager.sendTextMessage(formatPhoneNum(address), null, msg, mSendPI, mDeliverPI);
                }
            } else {
                SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(subIdTwo);
                PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new Intent(Context.TELEPHONY_SUBSCRIPTION_SERVICE), PendingIntent.FLAG_ONE_SHOT);
                ArrayList<String> messages = SmsManager.getDefault().divideMessage(content);
                for (String msg : messages) {
                    message = msg;
                    smsManager.sendTextMessage(formatPhoneNum(address), null, msg, mSendPI, mDeliverPI);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Uri uri = data.getData();
                    String[] contact = getPhoneContacts(uri);
                    if (contact != null) {
                        name = contact[0];//姓名
                        number = contact[1];//手机号
                        Log.e("lyc", name + "::::" + number);
                        mEditText.setText(name);
                    }
                }
            }
        }
    }

    /**
     * 读取联系人信息
     *
     * @param uri
     */
    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            contact[1] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.i("contacts", contact[0]);
            Log.i("contactsUsername", contact[1]);
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    /**
     * 去掉手机号内除数字外的所有字符
     *
     * @param phoneNum 手机号
     * @return
     */
    private String formatPhoneNum(String phoneNum) {
        String regex = "(\\+86)|[^0-9]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.replaceAll("");
    }


    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter isSend;
        isSend = new IntentFilter(SMS_SEND_ACTIOIN);
        mSendReceiver = new mServiceReceiver();
        registerReceiver(mSendReceiver, isSend);

        IntentFilter isDelivered;
        isDelivered = new IntentFilter(SMS_DELIVERED_ACTION);
        mDeliveredReceiver = new mServiceReceiver();
        registerReceiver(mDeliveredReceiver, isDelivered);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mSendReceiver);
        unregisterReceiver(mDeliveredReceiver);
    }

    /**
     * 自定义mServiceReceiver重写BroadcastReceiver监听短信状态信息
     */
    private class mServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SMS_SEND_ACTIOIN)) {
                try {
                    switch (getResultCode()) {
                        case RESULT_OK:
                            showToast(getResources().getString(R.string.str_sms_sent_success));
                            ContentValues values = new ContentValues();
                            values.put("address", formatPhoneNum(address));
                            values.put("person", "");
                            values.put("protocol", "0");
                            values.put("read", "1");
                            values.put("type", "2");
                            values.put("body", message);
                            context.getContentResolver().insert(Uri.parse("content://sms/"), values);
                            ed_context.setText("");
                            finish();
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            showToast(getResources().getString(R.string.str_sms_sent_failed));
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            break;
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            } else if (intent.getAction().equals(SMS_DELIVERED_ACTION)) {
                try {
                    switch (getResultCode()) {
                        case RESULT_OK:
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            showToast(getResources().getString(R.string.str_sms_rec_failed));
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            break;

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        }
    }
}
